package cn.bellychang.wangzheng.stack;

import cn.bellychang.bobo.stack.Stack;

/**
 * 不支持扩容
 *
 * @author ChangLiang
 * @date 2021/1/27
 */
public class ArrayStack2 implements Stack<String> {

    /**
     * 数组
     */
    private String[] items;
    /**
     * 栈中元素个数
     */
    private int count;
    /**
     * 栈的大小
     */
    private int n;

    private static final int EXTEND_FACTOR = 2;

    public ArrayStack2(int n) {
        this.items = new String[n];
        this.n = n;
        this.count = 0;
    }

    @Override
    public int size() {
        return count;
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    /**
     * 入栈
     *
     * @param item
     * @return false: 入栈失败 true: 入栈成功
     */
    @Override
    public void push(String item) {
        if (count == n) {
            String[] newItems = new String[n * EXTEND_FACTOR];
            System.arraycopy(items, 0, newItems, 0, count);
            items = newItems;
            n = n * EXTEND_FACTOR;
        }
        items[count] = item;
        ++count;
    }

    /**
     * 出栈
     *
     * @return
     */
    @Override
    public String pop() {
        if (count == 0) {
            throw new RuntimeException("the stack is empty");
        }
        String tmp = items[count - 1];
        --count;
        return tmp;
    }

    @Override
    public String peek() {
        if (count == 0) {
            throw new RuntimeException("the stack is empty");
        }
        return items[count - 1];
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Stack Top{");
        for (int i = count - 1; i >= 0; i--) {
            builder.append(items[i]);
            builder.append("->");
        }
        return builder.toString().endsWith("->") ?
                builder.substring(0, builder.length() - 2) + "}"
                : builder.append("}").toString();

    }
}
